package com.agileai.portal.portlets.forum;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.hotweb.domain.core.Profile;
import com.agileai.hotweb.domain.core.User;
import com.agileai.portal.bizmoduler.forum.ForumSectionInfoTreeManage;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.extend.forum.ForumPrivilegeHelper;
import com.agileai.portal.portlets.BaseMashupPortlet;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
/**
 * generated by miscdp
 */
public class ForumReplyPostPortlet extends BaseMashupPortlet {
	
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);

		String contentIdParamKey = preferences.getValue("contentIdParamKey", null);
	    String contentIdDefValue = preferences.getValue("contentIdDefValue", null);

	    HttpServletRequest httpServletRequest = PortletRequestHelper.getRequestContext(request).getServletRequest();
	    String contentId = httpServletRequest.getParameter(contentIdParamKey);
	    if (StringUtil.isNullOrEmpty(contentId)) {
	    	contentId = contentIdDefValue;
	    }
      
	    if (StringUtil.isNullOrEmpty(contentId)) {
	    	request.setAttribute("content", "content is not defined,please check it !");
	    }
	    
	    ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
	    String fciId = forumSectionInfoTreeManage.getFciIdRecord(contentId);
	    if(fciId != null){
	    	Profile profile = (Profile)request.getUserPrincipal();
			User user = (User)profile.getUser();
			ForumPrivilegeHelper forumPrivilegeHelper = new ForumPrivilegeHelper(user);
			if(forumPrivilegeHelper.isModerator(fciId) || forumPrivilegeHelper.isForumAdmin()){
				request.setAttribute("showManageBtn", "showManageBtn");
			}
		    
		    List<DataRow> rsList = forumSectionInfoTreeManage.findRepliesInfoRecords(contentId);
		    String replyId = "";
		    String replyIds = "";
		    for(int i=rsList.size()-1;i>=0;i--){
		    	DataRow row = rsList.get(i);
		    	replyId = row.getString("FRI_ID");
		    	replyIds = replyId+","+replyIds;
		    }
		    request.setAttribute("replyIds", replyIds);
			request.setAttribute("total", rsList.size());
		    request.setAttribute("contentId", contentId);
		    request.setAttribute("portletId", request.getWindowID());
	    }
	    super.doView(request, response);
	}

	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String template = preferences.getValue("template", null);
		String contentIdParamKey = preferences.getValue("contentIdParamKey", null);
		String contentIdDefValue = preferences.getValue("contentIdDefValue", null);
		
		request.setAttribute("template", template);
		request.setAttribute("contentIdDefValue", contentIdDefValue);
		request.setAttribute("contentIdParamKey", contentIdParamKey);
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		
		String template = request.getParameter("template");
		String contentIdParamKey = request.getParameter("contentIdParamKey");
		String contentIdDefValue = request.getParameter("contentIdDefValue");

		PreferencesWrapper preferWapper = new PreferencesWrapper();			
		preferWapper.setValue("template", template);
		preferWapper.setValue("contentIdParamKey", contentIdParamKey);
		preferWapper.setValue("contentIdDefValue", contentIdDefValue);
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences()); 
		
		response.setPortletMode(PortletMode.VIEW);
	}
	

	@Resource(id="getAjaxData")
	public void getAjaxData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String html = "";
		try {
			Profile profile = (Profile)request.getUserPrincipal();
			User user = (User)profile.getUser();
			ForumPrivilegeHelper forumPrivilegeHelper = new ForumPrivilegeHelper(user);
			String userCode = user.getUserCode();
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
			String fuId = forumSectionInfoTreeManage.getFuIdRecord(userCode);
			String template = preferences.getValue("template", null);
		    String contentId = request.getParameter("contentId");
			int pageNum = Integer.parseInt(request.getParameter("pageNum"));
			int pageSize = Integer.parseInt(request.getParameter("pageSize"));
			if (template != null){
				if (template.startsWith("http://")){
					template = this.retrieveTemplate(request, template);
				}
				
			    DataRow infoRow = forumSectionInfoTreeManage.getManagePostInfoRecord(contentId);
			    if(infoRow != null){
			    	String fpmState = infoRow.getString("FPM_STATE");
				    String fciId = infoRow.getString("FCI_ID");
				    String fpmExpression = infoRow.getString("FPM_EXPRESSION_CODE");
				    String fpmUserId = infoRow.stringValue("FPM_USERID");
				    JSONObject jsonObject = new JSONObject();
				    jsonObject.put("fpmId",contentId);
				    jsonObject.put("fpmTitle",infoRow.getString("FPM_TITLE"));
				    JSONArray jsonArray = new JSONArray();
				    String fields[] = {"isHasEnd","FPM_ID","FRI_CONTENT","FRI_TIME","FU_NAME","CODE_NAME","FU_INTEGRAL","floor","imgUrl","FRI_USERID","FRI_ID","FRI_STATE","showReportBtn","showSharePointBtn","FRI_REPORT_NUM","forumReplrtRecords"};
					List<DataRow> rsList = forumSectionInfoTreeManage.findRepliesInfoRecords(contentId);
					jsonObject.put("reviewCount",rsList.size());
					if(rsList.size()>0){
						int max = 0;
						if((pageNum+1)*pageSize>rsList.size()){
							max = rsList.size();
						}else{
							max = (pageNum+1)*pageSize;
						}
						for(int i = pageNum*pageSize; i < max; i++){
							DataRow row = rsList.get(i);
							List<DataRow> recordList = forumSectionInfoTreeManage.findforumReplrtRecords(row.stringValue("FRI_ID"));
							String forumReplrtRecords ="";
							if(!recordList.isEmpty()){
								forumReplrtRecords ="举报信息:";
								for(int j=0;j<recordList.size();j++){
									DataRow dataRow = recordList.get(j);
									String frrTime = DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL,dataRow.getTimestamp("FRR_TIME"));
									forumReplrtRecords = forumReplrtRecords+"<br/>" +"&nbsp;举报类型:&nbsp;"+dataRow.getString("CODE_NAME")+"&nbsp;举报人:&nbsp;"+dataRow.getString("FU_NAME")+"&nbsp;举报时间:&nbsp;"+frrTime;
								}
							}
							Timestamp friTIme = row.getTimestamp("FRI_TIME");
							String sdate = DateUtil.format(10, friTIme);
							String friState = row.stringValue("FRI_STATE");
							String friUserId = row.stringValue("FRI_USERID");
							String fuProfile = row.stringValue("FU_PROFILE");
							if("DIFFICULT_TO_HELP".equals(fpmExpression) && fuId.equals(fpmUserId)){
								row.put("showSharePointBtn", "showSharePointBtn");
							}else{
								row.put("showSharePointBtn", "disShowSharePointBtn");
							}
							if("HAS_REPORT".equals(friState) || "HAS_REPORT" == friState){
								row.put("showReportBtn", "showReportBtn");
							}else if("HAS_CONFIRM_REPORT".equals(friState) || "HAS_CONFIRM_REPORT" == friState){
								row.put("showReportBtn", "hasConfirmReport");
							}else{
								row.put("showReportBtn", "disShowReportBtn");
							}
							row.put("forumReplrtRecords", forumReplrtRecords);
							if("HAS_CONFIRM_REPORT".equals(friState) || "HAS_CONFIRM_REPORT" == friState){
								row.put("FRI_CONTENT", "该帖子信息已经被举报!");
							}else{
								row.put("FRI_CONTENT", row.stringValue("FRI_CONTENT"));
							}
							row.put("FRI_USERID", row.stringValue("FRI_USERID"));
							row.put("FRI_ID", row.stringValue("FRI_ID"));
							row.put("friUserId", friUserId);
							row.put("FRI_TIME", sdate);
							row.put("FU_LEVEL",row.stringValue("CODE_NAME"));
							if(fuProfile.isEmpty()){
								row.put("imgUrl", "/portal/images/user_logined.png");
							}else{
								row.put("imgUrl", fuProfile);
							}
							row.put("FU_INTEGRAL", row.getInt("FU_INTEGRAL"));
							if("HAS_END".equals(fpmState)){
								row.put("isHasEnd","isHasEnd");
							}else{
								row.put("isHasEnd","disHasEnd");
							}
							if("楼主".equals(row.getString("FRI_REPORT_NUM"))){
								row.put("FRI_REPORT_NUM", row.getString("FRI_REPORT_NUM"));
							}else{
								row.put("FRI_REPORT_NUM", row.getString("FRI_REPORT_NUM")+"楼");
							}
							String floor = String.valueOf(i+1);
							row.put("floor", floor);
							JSONObject object = new JSONObject();
							if(forumPrivilegeHelper.isGuest()){
								object.put("isGuest", "isGuest");
							}else{
								object.put("isGuest", "disGuest");
							}
							String isSharePoint = row.getString("FRI_ISSHAREPOINT");
							if("Y".equals(isSharePoint) || "Y" == isSharePoint){
								object.put("isSharePoint",isSharePoint);
							}else{
								object.put("isSharePoint","N");
							}
							for(int j=0;j<fields.length;j++){												
								object.put(fields[j], row.stringValue(fields[j]));
								object.put("fpmId", contentId);
								object.put("num", i);
							}
							if(forumPrivilegeHelper.isModerator(fciId) || forumPrivilegeHelper.isForumAdmin()){
								object.put("showManageBtn", "showManageBtn");
							}else{
								object.put("showManageBtn", "disShowManageBtn");
							}
							jsonArray.put(object);
						}
					}
					
					jsonObject.put("datas", jsonArray);
					String ajaxData = jsonObject.toString();
					HashMap<String, String> map = this.buildVarMap(ajaxData);
					html = mergeReviewData(map, template);	
			    }else{
			    	JSONObject jsonObject = new JSONObject();
			    	jsonObject.put("reviewCount","");
			    	jsonObject.put("fpmId","");
				    jsonObject.put("fpmTitle","");
			    	JSONArray jsonArray = new JSONArray();
			    	JSONObject object = new JSONObject();
			    	object.put("isGuest", "");
			    	object.put("isSharePoint","");
			    	 String fields[] = {"isHasEnd","FPM_ID","FRI_CONTENT","FRI_TIME","FU_NAME","CODE_NAME","FU_INTEGRAL","floor","imgUrl","FRI_USERID","FRI_ID","FRI_STATE","showReportBtn","showSharePointBtn","FRI_REPORT_NUM","forumReplrtRecords"};
			    	for(int j=0;j<fields.length;j++){												
						object.put(fields[j], "");
						object.put("imgUrl", "user_logined.png");
						object.put("fpmId", "");
						object.put("num", "");
					}
			    	object.put("showManageBtn", "");
			    	jsonArray.put(object);
			    	jsonObject.put("datas", jsonArray);
					String ajaxData = jsonObject.toString();
					HashMap<String, String> map = this.buildVarMap(ajaxData);
					html = mergeReviewData(map, template);	
			    }
			}
		} catch (Exception e) {
			this.logger.error("获取数据失败getAjaxData", e);
		}				
		PrintWriter writer = response.getWriter();
		writer.print(html);
		writer.close();
	}
	
	private String retrieveTemplate(PortletRequest request, String dataURL) {
		String result = "";
		try {
			int index = dataURL.lastIndexOf("=");
			String templateId = dataURL.substring(index+1,dataURL.length());
			result = PortletCacheManager.getOnly().getCachedData("Y",templateId,dataURL, "0");
		} catch (Exception e) {
			this.logger.error("retrieve template error ", e);
		}
		return result;
	}
	
	private HashMap<String, String> buildVarMap(String json){
		HashMap<String,String> map = new HashMap<String,String>();
		ObjectMapper mapper = new ObjectMapper();
		try {
			map = mapper.readValue(json, new TypeReference<HashMap<String,Object>>(){});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String mergeReviewData(HashMap map,String template){
		String result = null;
		try {
			StringWriter writer = new StringWriter();
			
			String encoding = "utf-8";
	    	Configuration cfg = new Configuration();
	    	cfg.setTemplateLoader(new StringTemplateLoader(template));  
	    	cfg.setEncoding(Locale.getDefault(), encoding);
	        cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
	    	Template temp = cfg.getTemplate("");
	    	temp.setEncoding(encoding);
	        Map root = new HashMap();
	        root.put("model",map);
	        temp.process(root, writer);
	        writer.flush();
	        result = writer.toString();
		} catch (Exception e) { 
			e.printStackTrace();
			result = "";
		}
		return result;
	}

}
